import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:device_info/device_info.dart';
import 'package:fate_blind_box/chat_pages/chat_message_list/logic.dart';
import 'package:fate_blind_box/chat_pages/chat_message_list/view.dart';
import 'package:fate_blind_box/chat_pages/meet_home/logic.dart';
import 'package:fate_blind_box/chat_pages/meet_home/view.dart';
import 'package:fate_blind_box/config/event_bus.dart';
import 'package:fate_blind_box/config/event_keys.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/network/http_config.dart';
import 'package:fate_blind_box/network/http_request.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/main/blind_box_2.dart';
import 'package:fate_blind_box/ui/main/contact.dart';
import 'package:fate_blind_box/ui/main/home.dart';
import 'package:fate_blind_box/ui/main/personal.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/widget/keep_alive_wrapper.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../utils/default/common_config.dart';
import '../../utils/loading.dart';
import '../../utils/map/map_common_config.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class AppMain extends StatefulWidget {
  int currentIndex = 2;

  AppMain({Key? key, this.currentIndex = 2}) : super(key: key);

  @override
  State<AppMain> createState() => _NavigatorState();
}

class _NavigatorState extends State<AppMain> {
  final _checkColor = ThemeColor.appColor;
  final _normalColor = ThemeColor.textColor;

  final _tabs = ["首页", "消息", "遇见", "朋友", "我的"];
  final _tabIcons = ["ic_hh", "ic_hx", "ic_hm", "ic_hl", "ic_hw"];
  final List<Widget> _widgetOptions = [
    // const KeepAliveWrapper(child: HomeUi()),
    const KeepAliveWrapper(child: MeetHomePage()),
    const ChatMessageListPage(),
    // MessageUi(),
    const KeepAliveWrapper(child: BlindBox2Ui()),
    const KeepAliveWrapper(child: ContactUi()),
    const KeepAliveWrapper(child: PersonalUi())
  ];

  int _isWechat = 0;

  int? unreadCount;

  late String username;

  late StreamSubscription<Map<String, Object>> _locationListener;

  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  @override
  void initState() {
    super.initState();
    Get.lazyPut(() => ChatMessageListLogic());
    Get.lazyPut(() => MeetHomeLogic());
    initData();
    initEventBus();
    _initWechat();
    _checkInvite();
    hiddenPayLogic();
  }

  //获取所有未读消息数
  void initData() async {
    unreadCount =
        await EMClient.getInstance.chatManager.getUnreadMessageCount();
  }

  _checkInvite() {
    loading(() async {
      String inviteCode = await Provider.getCache("inviteCode");
      final userId = Provider.memberId;
      String token = HttpConfig.token;
      if (inviteCode.isNotEmpty && userId.isNotEmpty && token.isNotEmpty) {
        await Api.getInstance().invite(userId, inviteCode);
        Provider.getUserEaseName().then((value) {
          username = value;
        });
      }
      setState(() {
        _isWechat = 1;
      });
      dismissLoading();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: widget.currentIndex,
        onTap: (int index) {
          setState(() {
            print('页面切换');
            widget.currentIndex = index;
          });
          if(index == 1){
            final ChatMessageListLogic logic = Get.find<ChatMessageListLogic>();
            logic.onRefresh();
          }
        },
        type: BottomNavigationBarType.fixed,
        selectedIconTheme: IconThemeData(color: _checkColor),
        unselectedIconTheme: IconThemeData(color: _normalColor),
        selectedItemColor: _checkColor,
        unselectedItemColor: _normalColor,
        selectedFontSize: 12,
        unselectedFontSize: 12,
        items: [
          _buildTabs(0),
          _msgIteam(1),
          _buildTabs(2),
          _buildTabs(3),
          _buildTabs(4),
        ],
      ),
      body: _widgetOptions[widget.currentIndex],
    );
  }

  initEventBus() {
    EventBus.instance.addListener(EventKeys.chatUpdateBadge, (arg) {
      setState(() {
        unreadCount = arg;
      });
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    debugPrint("AdidChangeDependencies");
  }

  BottomNavigationBarItem _msgIteam(int index) {
    return BottomNavigationBarItem(
      icon: unreadCount != null && unreadCount! > 0
          ? Badge(
              label: Text(
                ' $unreadCount ',
                style: TextStyle(fontSize: 8.sp, color: Colors.white),
              ),
              child: Image.asset(
                "images/${_tabIcons[index]}${index == widget.currentIndex ? "c" : "n"}.png",
                width: 24.w,
                height: 24.w,
              ),
            )
          : Image.asset(
              "images/${_tabIcons[index]}${index == widget.currentIndex ? "c" : "n"}.png",
              width: 24.w,
              height: 24.w,
            ),
      label: '消息',
    );
  }

  BottomNavigationBarItem _buildTabs(int index) {
    return BottomNavigationBarItem(
      icon: Image.asset(
        "images/${_tabIcons[index]}${index == widget.currentIndex ? "c" : "n"}.png",
        width: 24,
        height: 24,
      ),
      label: _tabs[index],
    );
  }

  void hiddenPayLogic() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo.version;
    var type =  await deviceModel;
    print('参数:$type====$version');
    var res = await HttpRequest.request('member/version/isPay', params: {
      'istep': version,
      'versionType':type,
    });
    if (res['code'] == 0) {
      CommonConfig.isHiddenOpen = res['data'] ?? 1;
    }
  }

  /// 获取手机型号
  Future<String> get deviceModel async{
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      log('制造商:${androidInfo.manufacturer}');
      return androidInfo.manufacturer.toLowerCase();
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      String model = iosInfo.model;
      if (kDebugMode) {
        print('iOS 手机型号：$model');
      }
      return 'apple';
    }
    return '';
  }

  Future? _initWechat() async {
    return fluwx.registerWxApi(
        appId: Provider.wechatAppID,
        doOnAndroid: true,
        doOnIOS: true,
        universalLink: HttpConfig.baseUrl
        // universalLink: "${HttpConfig.baseUrl}ios"
        );
  }

  void getCurrentLocation() async {
    /// [hasShow] 隐私权政策是否弹窗展示告知用户
    AMapFlutterLocation.updatePrivacyShow(true, true);

    /// [hasAgree] 隐私权政策是否已经取得用户同意
    AMapFlutterLocation.updatePrivacyAgree(true);

    /// 动态申请定位权限
    requestPermission();
    AMapFlutterLocation.setApiKey(
        MapCommonConfig.androidKey, MapCommonConfig.iosMapKey);

    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    _startLocation();

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      if (kDebugMode) {
        print('定位结果：$result');
      }
    });
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
    } else {
      toast('请打开定位权限');
    }
  }

  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
    } else {}
  }

  ///开始定位
  void _startLocation() {
    ///开始定位之前设置定位参数
    _setLocationOption();
    _locationPlugin.startLocation();
  }

  ///设置定位参数
  void _setLocationOption() {
    AMapLocationOption locationOption = AMapLocationOption();

    ///是否单次定位
    locationOption.onceLocation = true;

    ///是否需要返回逆地理信息
    locationOption.needAddress = true;

    ///逆地理信息的语言类型
    locationOption.geoLanguage = GeoLanguage.DEFAULT;

    locationOption.desiredLocationAccuracyAuthorizationMode =
        AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

    locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

    ///设置Android端连续定位的定位间隔
    locationOption.locationInterval = 2000;

    locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

    ///设置iOS端的定位最小更新距离<br>
    locationOption.distanceFilter = -1;

    locationOption.desiredAccuracy = DesiredAccuracy.HundredMeters;

    ///设置iOS端是否允许系统暂停定位
    locationOption.pausesLocationUpdatesAutomatically = false;

    ///将定位参数设置给定位插件
    _locationPlugin.setLocationOption(locationOption);
  }
}
